<?php

class BackendModule extends CWebModule
{
	public function init()
	{
		// this method is called when the module is being created
		// you may place code here to customize the module or the application

		// import the module-level models and components
		$this->setImport(array(
			'backend.models.*',
			'backend.components.*',
		));

        //这里重写父类里的组件
        //如有需要还可以参考API添加相应组件
        Yii::app()->setComponents(array(
            /*'errorHandler'=>array(
                'class'=>'CErrorHandler',
                'errorAction'=>'backend/default/error',
            ),*/
            'user'=>array(
                'class'=>CWebUser::class,//后台登录类实例
                'stateKeyPrefix'=>'admin',//后台session前缀
                'loginUrl'=>Yii::app()->createUrl('backend/default/login'),
            ),
        ));

	}

	public function beforeControllerAction($controller, $action)
	{
        if(parent::beforeControllerAction($controller, $action))
        {
            $route=$controller->id.'/'.$action->id;

            if(!$this->allowIp(Yii::app()->request->userHostAddress) && $route!=='default/error'){
                throw new CHttpException(403,"You are not allowed to access this page.");
            }

            $publicPages=array('default/login', 'default/error', 'default/captcha');
            //var_dump(Yii::app()->user);exit;
            if(Yii::app()->user->isGuest && !in_array($route,$publicPages))
                Yii::app()->user->loginRequired();
            else
                return true;
        }
        return false;

	}

    public function beforeAction(){
        if ( isset($_SESSION['hl_language']) && !empty($_SESSION['hl_language']))
        {
            Yii::app()->language = $_SESSION['hl_language'];
        }
    }

    /**
     * @param $ip
     * @return bool
     */
    protected function allowIp($ip) {
        if(empty($this->ipFilters))
            return true;
        foreach($this->ipFilters as $filter) {
            if($filter==='*' || $filter===$ip || (($pos=strpos($filter,'*'))!==false && !strncmp($ip,$filter,$pos)))
                return true;
        }
        return false;
    }


}
